package com.mspbots.rule.exceptions.cw;

import com.mspbots.cw.request.TenantTimeEntryDTO;
import lombok.extern.slf4j.Slf4j;
import org.jeasy.rules.annotation.Condition;
import org.jeasy.rules.annotation.Fact;
import org.jeasy.rules.annotation.Rule;

import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * @author Dinnes Zhang
 * @date
 */
@Slf4j
@Rule(name = "AfterHour", description = "")
public class AfterHour extends CwBaseRule implements IcwBaseRule {

    @Override
    @Condition
    public boolean condition(@Fact(FACT) TenantTimeEntryDTO entry) {
        try {
            if (!setUserMapping(entry.getTenantUserId()) || super.checkMessage(entry)) {
                return false;
            }
            if (!entry.getExtend().findPath("workType").get("name").asText().toLowerCase().contains("bus")) {
                return false;
            }
            LocalDateTime workTime = LocalDateTime.now().plusHours(Integer.parseInt(tenantUserMappingDTO.getTz().substring(0, 3)));
            LocalDateTime beginWork = LocalDateTime.of(workTime.toLocalDate(), LocalTime.MIN).plusHours(8);
            LocalDateTime endWork = LocalDateTime.of(workTime.toLocalDate(), LocalTime.MIN).minusHours(7);
            LocalDateTime beginDate = entry.getBeginDate().plusHours(Integer.parseInt(tenantUserMappingDTO.getTz().substring(0, 3)));
            LocalDateTime endDate = entry.getEndDate().plusHours(Integer.parseInt(tenantUserMappingDTO.getTz().substring(0, 3)));
            if ((beginDate.isAfter(beginWork) || beginDate.isEqual(beginWork)) && (endDate.isBefore(endWork) || endDate.isEqual(endWork))) {
                return false;
            }
        } catch (Exception e) {
            log.error("AfterHour rule execute error [{}] : {}", e.getStackTrace()[0].getLineNumber(), e.getMessage());
            e.printStackTrace();
        }
        return true;
    }
}
